#ifndef ____ROUTINE_HPP____
#define ____ROUTINE_HPP____

#include <iostream>
#include <vector>
#include "Addr.hpp"
#include "mutex.hpp"

class Routine
{
private:
    bool IsExits(const Inet_Addr &user)
    {
        for (auto &_use : _user)
        {
            if (_use == user)
                return true;
        }
        return false;
    }

    bool AddUser(const Inet_Addr &user)
    {
        if (IsExits(user))
        {
            return false;
        }
        _user.push_back(user);

        return true;
    }

    void SendMessageToAll(int _sockfd, const std::string message, Inet_Addr _addr)
    {
        for (auto &user : _user)
        {
            sendto(_sockfd, message.c_str(), message.size(), 0, user.Addr(), user.Size());
        }
    }

    void DeleteUser(const std::string message, Inet_Addr &_addr)
    {
        if (message == "quit")
        {
            auto iterator = _user.begin();
            while (iterator != _user.end())
            {
                if (*iterator == _addr)
                {
                    _user.erase(iterator);
                }
            }
        }
    }

public:
    Routine()
    {
    }

    ~Routine()
    {
    }

    void Start(int _sockfd, const std::string message, Inet_Addr _addr)
    {
        {
            Mutex::mutex _lock(_mutex);
            AddUser(_addr);
            SendMessageToAll(_sockfd, message, _addr);
            DeleteUser(message, _addr);
        }
    }

private:
    std::vector<Inet_Addr> _user;
    Mutex::mutex _mutex;
};

#endif